package com.nio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.Set;

/**
 * @Author 咕唧
 * @Date 2022/7/6 21:16
 * @Version 1.0
 */
public class NIO08Client {
    public static void main(String[] args) throws Exception {
        //先搞一个selector
        Selector selector = Selector.open();
        // 搞一个通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        //客户端关心的是连接成功
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        //客户端要连接服务端
        socketChannel.connect(new InetSocketAddress("10.9.48.142", 23456));
        while (true) {
            //判断是否有数据
            selector.select();
            //拿到所有的selectionKeys
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            selectionKeys.forEach(selectionKey -> {
                //获取通道
                SocketChannel channel = (SocketChannel) selectionKey.channel();
                try {
                    //判断通道是否是连接状态
                    if (channel.isConnectionPending()) {
                        //完成连接
                        channel.finishConnect();
                        //给服务器发送一条欢迎消息
                        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
                        String msg = "hello!";
                        byteBuffer.put(msg.getBytes("gbk"));
                        //翻转
                        byteBuffer.flip();
                        //发送给服务端
                        channel.write(byteBuffer);
                        //关注收消息,有数据可以读
                        channel.register(selector, SelectionKey.OP_READ);
                        sendMsg(channel);

                    } else if (selectionKey.isReadable()) {
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取收到的数据
                        while (true) {
                            byteBuffer.clear();
                            int read = channel.read(byteBuffer);
                            if (read > 0) {
                                byteBuffer.flip();
                                String msg = String.valueOf(Charset.forName("gbk").decode(byteBuffer));
                                System.out.println(msg);
                            } else {
                                break;
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            //清理
            selectionKeys.clear();
        }
    }

    public static void sendMsg(SocketChannel socketChannel) {
        new Thread() {
            @Override
            public void run() {
                System.out.println("请输入需要需要发送的数据");
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                Scanner input = new Scanner(System.in);
                while (true) {
                    try {
                        if (input.hasNext()) {
                            byteBuffer.clear();
                            String next = input.next();

                            byteBuffer.put(next.getBytes("gbk"));
                            byteBuffer.flip();
                            socketChannel.write(byteBuffer);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }
}
